'ui';

let storage = storages.create('md')
//A2F8A6CA80E8E8A8183D398AB7545C
let token = storage.get('token', '')

let username = storage.get('username', '')
let password = storage.get('password', '')
let sid = storage.get('sid', '')

let tip = 0
let appList = storage.get('appList', [{ name: '微信' }])

events.on('exit', function () {
	storage.put('appList', appList)
	storage.put('token', token)
	storage.put('username', username)
	storage.put('password', password)
	storage.put('sid', sid)
	console.hide()
})

let isRunning = false
ui.statusBarColor('#40a5f3')
ui.layout(
	<vertical>
		<appbar bg="#40a5f3">
			<toolbar title="美的xx" />
		</appbar>
		<Switch
			gravity="right"
			id="autoService"
			text="无障碍服务"
			checked="{{auto.service != null}}"
			padding="8 8 8 8"
			textSize="15sp"
		/>
		<horizontal>
			<text text="用户名" w="100" padding="30 0 10" gravity="center|right" />
			<input
				id="username"
				gravity="center"
				w="150"
				textSize="12sp"
				text="{{username}}"
			/>
		</horizontal>
		<horizontal>
			<text text="密码" w="100" padding="30 0 10" gravity="center|right" />
			<input
				id="password"
				gravity="center"
				w="150"
				textSize="12sp"
				text="{{password}}"
			/>
		</horizontal>
		<horizontal>
			<text text="项目id" w="100" padding="30 0 10" gravity="center|right" />
			<input id="sid" gravity="center" w="150" textSize="12sp" text="{{sid}}" />
		</horizontal>
		<ScrollView layout_weight="1" margin="60 30 0 0">
			<list id="appList" w="*" h="auto" textSize="12sp">
				<horizontal>
					<input
						id="appName"
						gravity="center"
						w="100"
						textSize="12sp"
						text="{{name}}"
					/>
					<frame w="auto" margin="10 0 10 0" h="auto" layout_gravity="center">
						<img
							w="*"
							h="*"
							src="#00000000"
							borderWidth="1dp"
							scaleType="fitXY"
							borderColor="#40a5f3"
							circle="true"
						/>
						<text
							id="del"
							h="auto"
							text="删除"
							padding="10 4 10 4"
							gravity="center"
							textSize="12sp"
							textColor="#40a5f3"
						/>
					</frame>
				</horizontal>
			</list>
		</ScrollView>
		<horizontal marginTop="20" gravity="center">
			<frame w="auto" margin="10 0 10 0" h="auto" layout_gravity="center">
				<img
					w="*"
					h="*"
					src="#00000000"
					borderWidth="1dp"
					scaleType="fitXY"
					borderColor="#40a5f3"
					circle="true"
				/>
				<text
					id="add"
					h="auto"
					text="添加"
					padding="10 4 10 4"
					gravity="center"
					textSize="12sp"
					textColor="#40a5f3"
				/>
			</frame>
		</horizontal>
		<horizontal marginTop="20" marginBottom="20" gravity="center">
			<frame w="auto" h="auto" layout_gravity="center">
				<img
					w="*"
					h="*"
					src="#00000000"
					borderWidth="1dp"
					scaleType="fitXY"
					borderColor="#40a5f3"
					circle="true"
				/>
				<text
					id="start"
					h="auto"
					text="开始运行"
					padding="10 4 10 4"
					gravity="center"
					textSize="12sp"
					textColor="#40a5f3"
				/>
			</frame>
			<frame w="auto" h="auto" marginLeft="10" layout_gravity="center">
				<img
					w="*"
					h="*"
					src="#00000000"
					borderWidth="1dp"
					scaleType="fitXY"
					borderColor="#40a5f3"
					circle="true"
				/>
				<text
					id="logout"
					h="auto"
					text="退出账号"
					padding="10 4 10 4"
					gravity="center"
					textSize="12sp"
					textColor="#40a5f3"
				/>
			</frame>
		</horizontal>
	</vertical>
)

ui.username.addTextChangedListener({
	afterTextChanged: function (context) {
		username = context.toString().trim()
		storage.put('username', username)

	},
})
ui.password.addTextChangedListener({
	afterTextChanged: function (context) {
		password = context.toString().trim()
		storage.put('password', password)
	},
})
ui.sid.addTextChangedListener({
	afterTextChanged: function (context) {
		sid = context.toString().trim()
		storage.put('sid', sid)
	},
})

ui.appList.setDataSource(appList)
ui.add.on('click', function () {
	appList.push({ name: '微信' })
	storage.put('appList', appList)
})

ui.appList.on('item_bind', function (itemView, itemHolder) {
	itemView.appName.addTextChangedListener({
		afterTextChanged: function (context) {
			itemHolder.item['name'] = context.toString().trim()
			console.log(itemHolder.item['name'])
		},
	})

	itemView.del.on('click', function () {
		// appList.splice(appList.indexOf(itemHolder), 1)
		appList.splice(itemHolder.position, 1)
	})
})

ui.autoService.on('check', function (checked) {
	// 用户勾选无障碍服务的选项时，跳转到页面让用户去开启
	if (checked && auto.service == null) {
		app.startActivity({
			action: 'android.settings.ACCESSIBILITY_SETTINGS',
		})
	}
	if (!checked && auto.service != null) {
		auto.service.disableSelf()
	}
})

// 当用户回到本界面时，resume事件会被触发
ui.emitter.on('resume', function () {
	// 此时根据无障碍服务的开启情况，同步开关的状态
	ui.autoService.checked = auto.service != null
})

ui.start.on('click', function () {
	// 程序开始运行之前判断无障碍服务
	if (auto.service == null) {
		toast('请先开启无障碍服务！')
		return
	}

	if (isRunning) {
		isRunning = false
		tip = 0
		ui.run(function () {
			ui.start.setText('开始运行')
		})
		threads.shutDownAll()
		return
	}
	toast('开始运行')
	isRunning = true
	ui.run(function () {
		ui.start.setText('停止运行')
	})

	threads.start(function () {
		main()
	})
})

ui.logout.on('click', function () {
	// 程序开始运行之前判断无障碍服务
	if (auto.service == null) {
		toast('请先开启无障碍服务！')
		return
	}
	isRunning = false
	tip = 0
	threads.shutDownAll()
	threads.start(function () {
		logout()
	})
})

function logout() {
	console.clear()
	console.show()
	nextWX()
	while (true) {
		try {
			//公众号
			intoGzh()
			exitAcc()
		} catch (error) {}
	}
}

function exitAcc() {
	if (text('个人中心').clickable(false).visibleToUser().exists()) {
		exitLogin()
		sleep(1000)
		nextWX()
	}
}

function main() {
	console.clear()
	console.show()
	nextWX()
	while (true) {
		try {
			//公众号
			intoGzh()
			//美的报修
			mdPage()
			//注册
			register()
		} catch (error) {}
	}
}

function intoGzh() {
	if (!text('通讯录').visibleToUser().exists()) {
		return
	}
	text('通讯录').visibleToUser().findOne(1000).parent().parent().click()
	text('公众号').findOne(3000).parent().parent().parent().click()
	desc('搜索')
		.className('android.widget.ImageView')
		.visibleToUser()
		.findOne(3000)
		.click()
	className('android.widget.EditText').findOne(2000).setText('美的服务')

	// text('美的服务').childclassName('android.widget.TextView').visibleToUser().findOne(2000).parent().paret().parent().parent().click()
	// className('android.widget.ListView').findOne(2000).child(0).click()

	try {
		try {
			className('android.widget.ListView').findOne(2000).child(0).click()
		} catch (error) {
			
		}
		className('android.widget.ListView').findOne(2000).child(1).click()
	} catch (err) {
		console.log(err)
		let bounds = text('美的服务')
			.childclassName('android.widget.TextView')
			.visibleToUser()
			.findOne(2000)
			.parent()
			.bounds()
		console.log(bounds)
		console.hide()
		click(bounds.centerX(), bounds.centerY())
		click(bounds.centerX(), bounds.centerY())
		console.show()
	}
	sleep(1000)
}
function mdPage() {
	if (!text('报装报修').visibleToUser().exists()) {
		return
	}
	text('报装报修')
		.clickable(false)
		.visibleToUser()
		.findOne(3000)
		.parent()
		.parent()
		.click()
	text('报装报修').clickable().visibleToUser().findOne(3000).click()
	sleep(3000)
}
function register() {
	if (!text('预约安装维修').visibleToUser().exists()) {
		return
	}

	let parent = null
	try {
		parent = text('请验证您的手机号码*').findOne(2000).parent()
	} catch (error) {
		console.log('用户已经登录')
		nextWX()
	}
	// phone
	let phone = getPhone()
	toastLog(phone)
	parent.child(3).setText(phone)
	// setText(phone)
	sleep(300)
	text('发送验证码').findOne(1000).click()
	sleep(10000)
	// code
	let code = 0
	let isOK = false
	for (let i = 0; i < 6; i++) {
		code = getCodeByPhone(phone)
		console.log(code);
		if (code.length == 6) {
			isOK = true
			break
		}
		console.log('等10s')
		sleep(10000)
	}
	if (!isOK) {
		desc('返回')
			.className('android.widget.ImageView')
			.findOne(1000)
			.parent()
			.click()
	}

	parent.child(5).setText(code)
	text('立即绑定').findOne(1000).click()
	// text('提交').visibleToUser().findOne(2000).parent().click()
	sleep(1000)

	// 检查是否有绑定
	let isBind = checkbind()
	if (isBind) {
		// 退出登录
		desc('返回')
			.className('android.widget.ImageView')
			.findOne(1000)
			.parent()
			.click()
		exitLogin()
	} else {
		// 没有绑定 切换下一个app
		nextWX()
		sleep(2000)
	}
}

function checkbind() {
	text('请选择联系人').findOne(1000).parent().click()
	let isBind =
		textStartsWith('已有联系人').findOne(3000).text() != '已有联系人(0)'
	sleep(2000)
	back()
	sleep(2000)
	if (textStartsWith('已有联系人').exists()) {
		back()
	}
	return isBind
}
function exitLogin() {
	text('个人中心')
		.clickable(false)
		.visibleToUser()
		.findOne(2000)
		.parent()
		.parent()
		.click()
	text('个人中心').clickable().visibleToUser().findOne(3000).click()
	sleep(3000)

	while (!textContains('登记家电').visibleToUser().exists()) {}
	text('美的服务')
		.className('android.webkit.WebView')
		.visibleToUser()
		.findOne(10000)
		.findOne(className('android.widget.Image'))
		.parent()
		.click()

	text('退出登录').findOne(2000).parent().parent().parent().click()
	sleep(2000)
	click(758, 1311)
	click(758, 1311)
	sleep(1000)
	desc('返回')
		.className('android.widget.ImageView')
		.findOne(1000)
		.parent()
		.click()
}

function getPhone() {
	if (token == '') {
		// login
		login()
	}

	let data = request('/getPhone', {
		token: token,
		sid: sid,
	})

	if (data['msg'] == 'success') {
		return data['phone']
	} else {
		throw '获取手机号失败'
	}
}

function getCodeByPhone(phone) {
	//sleep(15000)
	phone = Number(phone)
	let data = request('/getMessage', {
		token: token,
		sid: sid,
		phone: phone,
	})
	//console.log(data)
	// if (Number(data['code']) < 0) {
	//     throw '获取验证码失败'
	// }

	if (Number(data['code']) == 0) {
		let codeStr = data['sms']
		let code = codeStr.match(/(\d+)/g)[0]
		return code
	} else {
		return data['msg']
		// return false
		// sleep(10000)
		// return getCodeByPhone(phone)
	}
}

function login() {
	toastLog('登录中')
	let data = request('/login', {
		username: username,
		password: password,
	})
	sleep(5000)
	if (data['msg'] == 'success') {
		token = data['token']
		toastLog('登录成功')
		sleep(3000)
		return token
	} else {
		throw '登录失败'
	}
}

function request(url, data) {
	let params = '?'
	for (let name in data) {
		params += name
		params += '='
		params += data[name]
		params += '&'
	}
	params = params.substring(0, params.length - 1)
	let doMain = 'http://www.huli667.com:81/sms/api'
	let res = http.get(doMain + url + params)
	if (res.statusCode != 200) {
		throw '接码失败'
	}
	return res.body.json()
}

function nextWX() {
	if (tip >= appList.length) {
		exit()
	}
	let appName = appList[tip]['name']
	home()
	sleep(300)
	home()
	sleep(300)
	let appObj = null
	for (let i = 0; i < 5; i++) {
		if (
			(appObj = text(appName).id('item_title').visibleToUser().findOne(1000))
		) {
			// if ((appObj = text(appName).visibleToUser().findOne(1000))) {
			let bounds = appObj.parent().bounds()
			console.hide()
			sleep(1000)
			click(bounds.centerX(), bounds.centerY())
			// click(bounds.centerX(), bounds.centerY())
			sleep(1000)
			console.show()
			tip++
			sleep(3000)
			if (text(appName).id('item_title').visibleToUser().exists()) {
				tip--
				nextWX()
			}
			return
		} else {
			swipe(device.width - 30, device.height / 2, 30, device.height / 2, 500)
		}
	}
}
